﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;

namespace MsDbToSql
{
    public class TableToEntity
    {
        public string NameSpace { get; set; }
        //public string TableName { get; set; }

        private DbOprator Dbo;

        public TableToEntity(DbOprator dbo)
        {
            this.NameSpace = "MySchool.Models";
            this.Dbo = dbo;
        }

        public string GetClassCode(string TableName)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Text;");
            sb.AppendLine("namespace "+NameSpace+"{");
            sb.AppendLine("\t[Serializable]");
            sb.AppendLine("\tpublic class "+TableName+"{");
            //属性开始
            string sql = string.Format(@"select field=c.name,type=t.name
                                from syscolumns as c inner join systypes as t on c.xtype = t.xtype
                                where id = object_id('{0}') and t.status = 0", TableName);
            SqlDataReader reader = SQLHelper.ExcuteReader(sql);
            while(reader.Read())
            {
                sb.AppendFormat("\t\tpublic {0} {1} {{ get; set; }}", getType(reader["type"].ToString()), reader["field"]);
                sb.AppendLine("\n");
            }
            reader.Close();
            //属性结束
            sb.AppendLine("\t}");  
            sb.AppendLine("}");
            return sb.ToString();
        }
        private string getType(string dbType)
        {
            
            string type = "string";
            if (dbType == "char" || dbType == "varchar" || dbType == "nchar" || dbType == "nvarchar")
                type = "string";
            else if (dbType == "int" || dbType == "bigint")
                type = "int";
            else if (dbType == "float" || dbType == "money" || dbType == "real" || dbType == "decimal")
                type = "double";
            else if (dbType == "datetime")
                type = "DateTime";
            
            return type;
        }

        public void SaveFiles(string TableName,string path)
        {
            //检测命名空间对应的目录是否存在
            string dir = NameSpace.Replace(".",@"\");
            path = path + "\\"+dir;
            if (! Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //保存文件
            using (StreamWriter writer = new StreamWriter(path + @"\" + TableName + ".cs"))
            {
                writer.Write(GetClassCode(TableName));
            }
        }

    }
}
